package wenjun.du.androidart.ipc.messenger

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log
import android.widget.Toast

class MessengerService : Service() {
    companion object {
        private const val TAG = "MessengerService"
    }

    private lateinit var mHandler: Handler
    override fun onBind(intent: Intent): IBinder {
        return Messenger(mHandler).binder
    }

    override fun onCreate() {
        super.onCreate()
        mHandler = object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                //处理客户端发送的消息
                when (msg.what) {
                    1 -> {
                        Toast.makeText(
                            this@MessengerService,
                            "${msg.data.getString("data")}",
                            Toast.LENGTH_SHORT
                        )
                            .show()
                        val obtain = Message.obtain()
                        val bundle = Bundle()
                        bundle.putString("service_data", "hello 我是来自服务端的问候")
                        obtain.data = bundle
                        obtain.what = 2
                        msg.replyTo.send(obtain)
                    }
                }
            }
        }
    }
}